<template>
  <vx-card class="pt-5" full>
    <div class="siteSearchTop">
      <div class="siteSearch">
        <vs-input
          label="桥梁名称"
          size="small"
          icon="icon-search"
          icon-pack="feather"
          icon-after="true"
          class="inputx no-icon-border"
          v-model="searchList.name"
          @blur="filterSite()"
        />
      </div>
      <vs-button
        color="primary"
        icon-pack="feather"
        icon="icon-plus"
        @click="addUser"
        size="small"
      >新增</vs-button>
    </div>
    <!-- 表格及分页组件 -->
    <vx-table
      :data="tableData"
      :total="recordsTotal"
      class="mt-4"
      @current-change="currentChange"
      :pageSize="pageSize"
    >
      <!-- @current-change="currentChange" :pageSize="pageSize"-->
      <el-table-column label="图片" min-width="80">
        <template slot-scope="scope" align="center">
          <!-- <img
            :src="getImgUrl(scope.row.picId)"
            style="width: 40px;height:40px;margin:0 auto;"
            @click="openImg(scope.row.picId)"
          />-->
          <!-- <div style="margin: 100px 300px;">
          <div style="width: 300px;">-->

          <el-image
            style="width: 40px;height:40px;margin:0 auto;"
            :src="getImgUrl(scope.row.picId)"
            :preview-src-list="[getImgUrl(scope.row.picId)]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="桥梁名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="id" label="桥梁编号" min-width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="proType" label="工程类型" show-overflow-tooltip>
        <template v-slot="scope">
          <div v-for="(item,index) in proList " :key="index">
            <span v-if="item.code==scope.row.proType">{{item.name}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="builtArea" label="建筑面积" show-overflow-tooltip>
        <template v-slot="scope">{{scope.row.builtArea}}平方米</template>
      </el-table-column>
      <el-table-column prop="engineeringCost" label="工程造价" show-overflow-tooltip>
        <template v-slot="scope">{{scope.row.engineeringCost}}万元</template>
      </el-table-column>
      <el-table-column prop="contractDuration" label="合同工期" show-overflow-tooltip></el-table-column>
      <el-table-column prop="startDate" label="开始时间" show-overflow-tooltip></el-table-column>
      <el-table-column prop="endDate" label="结束时间" show-overflow-tooltip></el-table-column>
      <el-table-column prop="builder" label="施工单位" show-overflow-tooltip></el-table-column>
      <el-table-column prop="builderMgr" label="施工单位负责人" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" min-width="120">
        <template v-slot="scope">
          <feather-icon
            icon="EditIcon"
            :svgClasses="['stoke-current text-primary w-5 h-5']"
            class="cursor-pointer p-2"
            title="修改"
            @click.stop="handleEdit(scope.$index, scope.row)"
          />
          <feather-icon
            icon="Trash2Icon"
            :svgClasses="['stoke-current text-danger w-5 h-5']"
            class="cursor-pointer p-2"
            title="删除"
            @click.stop="handleDelete(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
    </vx-table>
    <el-dialog width="400px" :visible.sync="imgVisible" class="img-dialog">
      <el-card :body-style="{ padding: '0px' }">
        <img :src="dialogImgUrl" width="100%" height="100%" />
      </el-card>
    </el-dialog>
    <!--新增-编辑 模态框开始 -->
    <vx-popup
      width="650px"
      classContent="popup-example"
      :title="popTitle"
      :active.sync="popupActivoAdd"
      :isValid="isLatitude"
      @confirmPopup="saveData"
      @cancelPopup="popupActivoAdd = false"
    >
      <div class="vx-row">
        <div class="vx-col w-full md:w-1/2" style="paddingLeft:40px;paddingTop:5px">
          <vs-input
            label="项目名称："
            class="inputx mt-2 red"
            v-model="popList.name"
            name="项目名称"
            v-validate="'required'"
            data-vv-validate-on="input|blur"
          />
          <span
            class="text-danger text-sm"
            v-show="errorBags.has('项目名称')"
          >{{ errorBags.first('项目名称')}}</span>
          <!-- <vs-input label="类型：" class="inputx mt-2" v-model="popList.type" name="类型" /> -->
          <vs-input label="纬度：" class="inputx mt-2 red" v-model="popList.lat" name="纬度" />
          <vs-input label="建筑面积：" class="inputx mt-2" v-model="popList.builtArea" name="建筑面积" />
          <span class="ppp">平方米</span>
          <vs-input
            label="工程造价："
            class="inputx mt-2"
            v-model="popList.engineeringCost"
            name="工程造价"
          />
          <span class="ppp">万元</span>
          <vs-input
            label="合同工期："
            class="inputx mt-2"
            v-model="popList.contractDuration"
            name="合同工期"
          />
          <span class="ppp">年</span>
          <div class="popImg">
            <div class="imgTitle">
              <span style="color:red">*</span> 工程类型：
            </div>
            <div class="uploadImg mt-2 red">
              <el-select v-model="popList.proType" placeholder="请选择">
                <el-option
                  v-for="item in proList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </div>
          </div>
          <vs-input
            label="描述："
            class="inputx mt-2 red"
            v-model="popList.describe"
            name="描述"
            v-validate="'required'"
            data-vv-validate-on="input|blur"
          />
          <span class="text-danger text-sm" v-show="errorBags.has('描述')">{{ errorBags.first('描述')}}</span>
        </div>
        <div class="vx-col w-full md:w-1/2">
          <div class="popImg">
            <div class="imgTitle">开始时间：</div>
            <div class="uploadImg mt-2">
              <el-date-picker
                v-model="popList.startDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择开始日期"
              ></el-date-picker>
            </div>
          </div>
          <div class="popImg">
            <div class="imgTitle">结束时间：</div>
            <div class="uploadImg mt-2">
              <el-date-picker
                v-model="popList.endDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择结束日期"
              ></el-date-picker>
            </div>
          </div>

          <vs-input label="经度：" class="inputx mt-2 red" v-model="popList.lng" />
          <vs-input label="施工单位：" class="inputx mt-2" v-model="popList.builder" />
          <vs-input label="施工负责人：" class="inputx mt-2" v-model="popList.builderMgr" />
          <div class="popImg">
            <div class="imgTitle">
              <span style="color:red">*</span> 图片：
            </div>
            <div class="uploadImg mt-2">
              <div class="imgContainer mr-5">
                <span v-if="file">
                  <span class="handleImg">
                    <i class="el-icon-zoom-in" @click="handlePictureCardPreview"></i>
                    <i class="el-icon-delete" @click="handleRemove"></i>
                  </span>
                  <img :src="file || tableImageUrl" class="avatar" width="100%" />
                </span>
                <span v-else>
                  <span class="imgSize">100x100</span>
                </span>
              </div>
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="handleImagesUrlBefore"
                ref="upload"
              >
                <vs-button color="primary" size="small">上传图片</vs-button>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="50%" :src="dialogImageUrl || tableImageUrl" alt />
              </el-dialog>
            </div>
          </div>
        </div>
      </div>
    </vx-popup>
    <!-- 新增模态框结束 -->
    <!--删除模态框开始 -->
    <vx-popup
      classContent="popup-example"
      title="删除"
      width="400px"
      :active.sync="popupActivoDel"
      :isValid="true"
      @confirmPopup="delData"
      @cancelPopup="popupActivoDel = false"
    >
      <span>确定删除这条数据吗？</span>
    </vx-popup>
    <!-- 删除模态框结束 -->
  </vx-card>
</template>
<script>
import projectConfig from "@/../public/project.config.js";

import base from "@/api/base"; // 导入接口域名列表
export default {
  data() {
    return {
      srcList: [],
      uploadUrl: base.accessUPLOADURL, //图片上传网址
      file: "",
      popTitle: "新增",
      imgVisible: false,
      tableImageUrl: "./imgs/siteImg.png",
      dialogImgUrl: "",
      dialogImageUrl: "",
      dialogVisible: false,
      icon: "", //新增-上传图片路径 图片id
      iconPath: "",
      baseUrl: process.env.BASE_URL,
      searchList: {
        name: "",
      },
      tableData: [], //表格数据
      popList: {
        name: "",
        describe: "",
        lng: "",
        lat: "",
        picId: "",
        startDate: "",
        endDate: "",
        proType: "",
        builtArea: "",
        engineeringCost: "",
        contractDuration: "",
        builder: "",
        builderMgr: "",
      },
      popPasswordlist: {
        originalPassword: "",
        newPassword: "",
        confirmNewPassword: "",
      },
      popupActivoAdd: false,
      popupActivoDetails: false,
      popupActivoDel: false,
      siteId: "", // 项目id用于项目的修改
      recordsTotal: 0, //记录总数
      currentPage: 1, //当前页
      pageSize: 10,
      proList: [],
    };
  },
  methods: {
    //分页
    currentChange(currentPage) {
      this.currentPage = currentPage;
      this.filterSite(this.currentPage);
    },
    //查询类别
    queryProType() {
      this.$api.accessControl.queryProType().then((res) => {
        if (res.data.success) {
          this.proList = res.data.data;
        }
      });
    },
    // 查询项目
    filterSite(start) {
      let dataStart = 1;
      if (start) {
        dataStart = start;
      }
      // console.log(dataStart,"////")
      let params = {
        name: this.searchList.name, // .trim(),
        pageSize: this.pageSize,
        pageNumber: dataStart,
      };
      this.$api.accessControl
        .searchSite(params)
        .then((res) => {
          console.log(res.data.data.currentPageData);
          if (res.data.data.length > 0) {
            res.data.data.map((v) => {
              if (this.proList.length > 0) {
                this.proList.map((v1) => {
                  if (v.proType === v1.code) {
                    v.proName = v1.name;
                  }
                });
              }
            });
          }
          // console.log(res,"=====")
          this.tableData = res.data.data.currentPageData; // 接口返回数据
          this.recordsTotal = res.data.data.total_sum;
        })
        .catch();
    },
    // 下载项目图片
    getImgUrl(fileId) {
      if (!fileId) {
        return this.tableImageUrl;
      } else {
        return `${base.DOWNLOADURL}${fileId}`;
      }
    },
    // 展示图片
    // openImg(fileId) {
    //   this.imgVisible = true;
    //   if (fileId) {
    //     this.dialogImgUrl = `${base.DOWNLOADURL}${fileId}`;
    //   } else {
    //     this.dialogImgUrl = this.tableImageUrl;
    //   }
    // },
    //表格行新增
    addUser() {
      this.$validator.reset();
      this.popupActivoAdd = true;
      this.popTitle = "新增";
      this.siteId = "";
      // 重置
      Object.keys(this.popList).forEach((v) => {
        this.popList[v] = "";
      });
      this.file = "";
    },
    //表格行编辑
    handleEdit(index, row) {
      this.$validator.reset();
      this.popupActivoAdd = true;
      this.popTitle = "编辑";
      Object.keys(this.popList).forEach((v) => {
        row[v] == null ? (this.popList[v] = "") : (this.popList[v] = row[v]);
      });
      this.siteId = row.id;
      if (row.picId) {
        this.file = `${base.DOWNLOADURL}/${row.picId}`;
      } else {
        this.file = "";
      }
    },
    //新增、编辑确-确定
    saveData() {
      this.popupActivoAdd = false;
      let picId;
      let params = {};
      if (!this.siteId) {
        params = {
          ...this.popList,
          appKey: localStorage.getItem("app-key"),
          lat: Number(this.popList.lat),
          lng: Number(this.popList.lng),
        };
        this.$api.accessControl
          .addSite(params)
          .then((res) => {
            if (res.data.success) {
              this.filterSite(this.currentPage);
              this.$vs.notify({
                text: "添加成功",
                color: "success",
              });
            } else {
              this.$vs.notify({ text: "添加失败", color: "danger" });
            }
          })
          .catch();
      } else {
        let params = {
          ...this.popList,
          appKey: localStorage.getItem("app-key"),
          lat: Number(this.popList.lat),
          lng: Number(this.popList.lng),
          id: this.siteId,
        };
        this.$api.accessControl
          .updateSite(params)
          .then((res) => {
            if (res.data.success) {
              this.$vs.notify({ text: "修改成功", color: "success" });
              this.filterSite(this.currentPage);
            } else {
              this.$vs.notify({ text: "修改失败", color: "danger" });
            }
          })
          .catch();
        this.siteId = "";
      }
    },
    //表格行删除-弹窗
    handleDelete(index, rowData) {
      this.popupActivoDel = true;
      this.siteId = rowData.id;
    },

    //表格行删除-确定
    delData() {
      this.popupActivoDel = false;
      let param = {
        id: this.siteId,
      };
      this.$api.accessControl.delSite(param).then((res) => {
        if (res.data.success) {
          this.$vs.notify({
            text: "删除成功",
            color: "success",
          });
          this.filterSite(this.currentPage);
        } else {
          this.$vs.notify({ text: "删除失败", color: "danger" });
        }
      });
    },
    //图片预览
    handlePictureCardPreview() {
      this.dialogImageUrl = this.file;
      this.dialogVisible = true;
    },
    //图片删除
    handleRemove() {
      this.file = "";
      this.popList.picId = "";
    },
    //新增-图片上传
    handleAvatarSuccess(res, file) {
      // console.log(res);
      this.file = URL.createObjectURL(file.raw);
      this.popList.picId = res.data.successFiles[0].filePath; //上传文件的id
      console.log(this.popList.picId);
      // console.log("图片上传成功后信息：" + JSON.stringify(res));
    },
    //对图片的宽高做限制：
    handleImagesUrlBefore: function (file) {
      var _this = this;
      return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.onload = function (event) {
          var image = new Image();
          image.onload = function () {
            var width = this.width;
            var height = this.height;
            resolve();
          };
          image.src = event.target.result;
        };
        reader.readAsDataURL(file);
      });
    },
  },
  computed: {
    // 新增校验
    isLatitude() {
      // 经纬度的校验
      let lgReg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/; // 经度范围：-180.0000~180.0000;
      let laReg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/; // 纬度范围：-90.0000~90.0000
      let longitu, latitude;
      this.popList.lttd
        ? (longitu = lgReg.test(this.popList.lgtd))
        : (longitu = true);
      this.popList.lttd ? laReg.test(this.popList.lttd) : (latitude = true);
      return (
        !this.errorBags.any() &&
        this.popList.name != "" &&
        this.popList.proType != "" &&
        this.popList.describe !== "" &&
        this.popList.lng !== "" &&
        this.popList.lat !== "" &&
        longitu &&
        latitude &&
        this.popList.picId !== ""
      );
    },
    projectConfig() {
      return {
        siteImg: `${this.baseUrl + projectConfig.siteImg}`,
      };
    },
  },
  created() {
    this.queryProType();
    this.filterSite();
  },
  mounted() {

  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/baseColor.scss";
.siteSearchTop {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .vs-component .vs-con-input-label .vs-input {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 24rem;
    /deep/ .vs-input--label {
      margin-right: 0.8rem;
    }
    /deep/ .vs-inputx.vs-input--input.hasIcon.icon-after-input {
      padding: 0.7rem 1rem !important;
    }
  }
}
.vs-con-input-label {
  width: 216px;
}
// /deep/.vx-row {
//   height: 500px;
// }
.siteSearch {
  position: relative;
}
.title {
  display: flex;
  justify-content: space-between !important;
}
.addUserForm {
  display: flex;
  justify-content: space-between;
}
.addUserBtn {
  color: #fff;
  background: $mainColor;
}

// 新增上传图片-开始
i.el-icon-zoom-in {
  // color: #fff;
  font-weight: 600;
}
.popImg {
  // margin-left: 0.6rem;
  padding-top: 0.75rem;
  .imgTitle {
    font-size: 12px;
  }
}
.uploadImg {
  display: flex;
  justify-content: flex-start;
  align-items: flex-end;

  .imgContainer,
  .avatar {
    width: 5rem;
    height: 5rem;
    border-radius: 50%;
    display: block;
    background: $mainColor;
  }
  .handleImg {
    position: absolute;
    top: 40%;
    left: 30%;
  }
  .imgContainer {
    position: relative;
  }
  .imgSize {
    position: absolute;
    top: 40%;
    left: 15%;
    font-size: 12px;
  }
}
/deep/.el-dialog {
  width: 40%;
  height: 70%;
  .el-dialog__body {
    text-align: center;
  }
}
// 弹窗字体
// /deep/.vs-input--input.normal {
//   font-size: 11.9px;
// }
.ppp {
  float: right;
  position: relative;
  right: 60px;
  top: -30px;
}
/deep/.el-image-viewer__close {
    top: 120px;
    right: 40px;
    width: 40px;
    height: 40px;
    font-size: 40px;
}
/deep/.el-image-viewer__canvas{
  // max-height: 60%
/deep/.el-image-viewer__img {
    max-height: 60% !important;
}
}

</style>
